import React, { useState, useEffect } from 'react';
import { Modal, Descriptions, Tag, Typography, Space, Spin, message } from 'antd';
import { DatabaseOutlined } from '@ant-design/icons';
import { getCompatibilityRuleByRuleId, CompatibilityRule } from '../../../services/api';
import './RuleDetailModal.css';

const { Text } = Typography;

interface RuleDetailModalProps {
  visible: boolean;
  ruleId: string | null;
  onClose: () => void;
}

const RuleDetailModal: React.FC<RuleDetailModalProps> = ({
  visible,
  ruleId,
  onClose
}) => {
  const [loading, setLoading] = useState(false);
  const [ruleDetail, setRuleDetail] = useState<CompatibilityRule | null>(null);

  // 获取规则详情
  const fetchRuleDetail = async (id: string) => {
    try {
      setLoading(true);
      const response = await getCompatibilityRuleByRuleId(id);
      if (response.success) {
        setRuleDetail(response.data);
      } else {
        message.error('获取规则详情失败');
        setRuleDetail(null);
      }
    } catch (error) {
      console.error('获取规则详情失败:', error);
      message.error('获取规则详情失败，请检查网络连接');
      setRuleDetail(null);
    } finally {
      setLoading(false);
    }
  };

  // 监听ruleId变化
  useEffect(() => {
    if (visible && ruleId) {
      fetchRuleDetail(ruleId);
    }
  }, [visible, ruleId]);

  // 重置状态
  useEffect(() => {
    if (!visible) {
      setRuleDetail(null);
    }
  }, [visible]);

  // 获取严重程度标签颜色
  const getSeverityColor = (severity: string) => {
    switch (severity) {
      case 'HIGH': return 'red';
      case 'MEDIUM': return 'orange';
      case 'LOW': return 'yellow';
      case 'INFO': return 'blue';
      default: return 'default';
    }
  };

  // 获取严重程度显示文本
  const getSeverityText = (severity: string) => {
    switch (severity) {
      case 'HIGH': return '高危';
      case 'MEDIUM': return '中危';
      case 'LOW': return '低危';
      case 'INFO': return '信息';
      default: return severity;
    }
  };

  return (
    <Modal
      title={
        <Space>
          <Text strong style={{ fontSize: '16px' }}>规则详情</Text>
          {ruleDetail && (
            <Tag color="blue" className="rule-id-tag">
              {ruleDetail.ruleId}
            </Tag>
          )}
        </Space>
      }
      open={visible}
      onCancel={onClose}
      footer={null}
      width={900}
      className="rule-detail-modal"
      destroyOnClose
    >
      {loading ? (
        <div style={{ textAlign: 'center', padding: '40px 0' }}>
          <Spin size="large" />
          <div style={{ marginTop: 16, color: '#666' }}>
            正在加载规则详情...
          </div>
        </div>
      ) : ruleDetail ? (
        <Descriptions column={2} bordered size="middle">
          <Descriptions.Item label="规则名称" span={2}>
            <Text strong style={{ fontSize: '15px' }}>{ruleDetail.ruleName}</Text>
          </Descriptions.Item>
          <Descriptions.Item label="分类">
            <Tag color="green">{ruleDetail.category}</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="严重程度">
            <Tag color={getSeverityColor(ruleDetail.severity)}>
              {getSeverityText(ruleDetail.severity)}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="源数据库类型">
            <Space>
              <DatabaseOutlined style={{ color: '#fa8c16' }} />
              <Tag color="orange">{ruleDetail.sourceDbType}</Tag>
            </Space>
          </Descriptions.Item>
          <Descriptions.Item label="目标数据库类型">
            <Space>
              <DatabaseOutlined style={{ color: '#722ed1' }} />
              <Tag color="purple">{ruleDetail.targetDbType}</Tag>
            </Space>
          </Descriptions.Item>
          <Descriptions.Item label="状态" span={2}>
            <Tag color={ruleDetail.isActive ? 'green' : 'red'}>
              {ruleDetail.isActive ? '启用' : '禁用'}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="规则模式" span={2}>
            <Text code className="rule-pattern-code">{ruleDetail.rulePattern}</Text>
          </Descriptions.Item>
          <Descriptions.Item label="问题描述" span={2}>
            <Text style={{ whiteSpace: 'pre-wrap' }}>{ruleDetail.description}</Text>
          </Descriptions.Item>
          <Descriptions.Item label="修复建议" span={2}>
            <Text style={{ whiteSpace: 'pre-wrap' }}>{ruleDetail.suggestion}</Text>
          </Descriptions.Item>
          {ruleDetail.exampleSql && (
            <Descriptions.Item label="示例SQL" span={2}>
              <Text code className="example-sql-code">{ruleDetail.exampleSql}</Text>
            </Descriptions.Item>
          )}
          {ruleDetail.suggestedSql && (
            <Descriptions.Item label="建议SQL" span={2}>
              <Text code className="suggested-sql-code">{ruleDetail.suggestedSql}</Text>
            </Descriptions.Item>
          )}
          <Descriptions.Item label="创建时间">
            <Text type="secondary">
              {new Date(ruleDetail.createdAt).toLocaleString('zh-CN')}
            </Text>
          </Descriptions.Item>
          <Descriptions.Item label="更新时间">
            <Text type="secondary">
              {new Date(ruleDetail.updatedAt).toLocaleString('zh-CN')}
            </Text>
          </Descriptions.Item>
        </Descriptions>
      ) : (
        <div style={{ textAlign: 'center', padding: '40px 0' }}>
          <Text type="secondary">规则详情加载失败</Text>
        </div>
      )}
    </Modal>
  );
};

export default RuleDetailModal;
